<?php
namespace Home\Controller;
class YungoController extends BaseController
{
    /*
     * 一元云购首页
     */
    public function index(){
        $to = intval(I('to',0));
        if($to == 1){
            //清单
            $this->cartList();return;
        }else if($to == 2){
            //确认清单
            $this->checkOrder();return;
        }else if($to == 3){
            //所有商品列表
            $this->getGoodsList();return;
        }else if($to == 4){
            //商品详情
            $this->getGoodsDetails();return;
        }else if($to == 5){
            //往期商品
            $this->getOldGoods();return;
        }
        //获取最新揭晓
        $m = D('Yungo');
        $newAwary = $m->getNewAwary();
        $this->assign('newAwary',$newAwary);
        //获取人气商品
        $hotGoods = $m->getHotGoods();
        $this->assign('hotGoods',$hotGoods);
        //获取所有分类及商品
        $allGoods = $m->getAllGoods();
        $this->assign('allGoods',$allGoods);
        //获取最新上架
        $newGoods = $m->getNewGoods();
        $this->assign('newGoods',$newGoods);
        //获取云购清单
        $cartNum = count(json_decode(stripslashes(cookie('Cartlist')),true));
        $this->assign('cartNum',$cartNum);
        $this->display('Yungo/yun/index');
    }

    /***************************所有商品****************************/
    public function getGoodsList(){
        $mgoods = D('Home/Yungo');
        
        //获取商品列表
        $obj["areaId2"] = $areaId2;
        $obj["areaId3"] = $areaId3;
        $rslist = $mgoods->getGoodsList($obj);
        $brands = $rslist["brands"];
        $pages = $rslist["pages"];
        $goodsNav = $rslist["goodsNav"];
        $this->assign('goodsList',$rslist);
        $this->assign('c1Id',I("c1Id"));
        //获取分类
        $m = M('GoodsCats');
        $cat = $m->where('catId = '.I('c1Id'))->getField('catName');
        $this->assign('catName',$cat);
        $this->assign('c2Id',I("c2Id"));
        $this->assign('c3Id',I("c3Id"));
        $this->assign('bs',I("bs",0));
        $this->assign('msort',I("msort",1));
        $this->assign('sj',I("sj",0));
        $this->assign('stime',I("stime"));//上架开始时间
        $this->assign('etime',I("etime"));//上架结束时间
        
        $this->assign('areaId3',I("areaId3",0));
        $this->assign('communityId',I("communityId",0));
        
        $pricelist = explode("_",I("prices"));
        $this->assign('sprice',$pricelist[0]);
        $this->assign('eprice',$pricelist[1]);
        
        $this->assign('brandId',I("brandId",0));
        $this->assign('keyWords',urldecode(I("keyWords")));
        $this->assign('brands',$brands);
        $this->assign('goodsNav',$goodsNav);
        $this->assign('pages',$pages);
        $this->assign('prices',$prices);
        $priceId = $prices[I("prices")];
        $this->assign('priceId',(strlen($priceId)>1)?I("prices"):'');
        $this->assign('districts',$districts);
        //获取云购清单
        $cartNum = count(json_decode(stripslashes(cookie('Cartlist')),true));
        $this->assign('cartNum',$cartNum);
        $this->display('Yungo/yun/goodsList');
    }

    /****************************商品详情*****************************/
    public function getGoodsDetails(){
        $m = D('Yungo');
        $goods = $m->getGoodsDetails();
        $this->assign('goods',$goods);
        //获取云购清单
        $cartNum = count(json_decode(stripslashes(cookie('Cartlist')),true));
        $this->assign('cartNum',$cartNum);
        $this->display('Yungo/yun/goodsDetails');
    }
    //获取夺宝记录
    public function goRecord(){
        $itemid = intval($_GET['gid']);
        if (!$itemid) $this->error('参数错误');
        $cords=M()->query("select * from `__PREFIX__member_go_record` where `shopid`='$itemid' ");
        if(!$cords){
            $this->error('暂无购买记录');
        }
        $this->records = $cords;
        $this->item = M('shoplist')->where(array('id' => $itemid))->find();
        $this->title = '购买记录';
        $this->display('Yungo/yun/goRecord');
    }
    //往期商品
    public function getOldGoods(){
        $itemid=intval($_GET['gid']);
        $item = M('shoplist')->where(array('id' => $itemid))->find();
        if(!$item){
            $this->error('商品不存在！');
        }
        if (!$item['q_end_time']) {
            header("location: ".U('getGoodsDetails',array('gid' => $item['id'])));
            exit;
        }
        if(empty($item['q_user_code'])){
            $this->success('该商品正在进行中...');
        }
        $itemlist = M('shoplist')->where(array('sid' => $item['sid']))->order('qishu desc')->select();
        //获取分类信息
        $goodsCat = array();
        foreach($item as $k=>$v){
            if($k == 'mall_cateid' || $k == 'mall_cateid2' || $k == 'mall_cateid3'){
                $sql = "select catId,catName from __PREFIX__goods_cats where catId = ".$v;
                $goodsCat[$k] = M('Shoplist')->query($sql);
            }
        }
        $this->assign('goodsCat',$goodsCat);
        //购买中奖码
        $q_user = unserialize($item['q_user']);
        $q_user_code_len = strlen($item['q_user_code']);
        $q_user_code_arr = array();
        for($q_i=0;$q_i < $q_user_code_len;$q_i++){
            $q_user_code_arr[$q_i] = substr($item['q_user_code'],$q_i,1);
        }
        //期数显示
        $loopqishu='';
        $sql = "select id,qishu from __PREFIX__shoplist where sid = ".$item['sid']." order by qishu desc";
        $loopqishu = M('Shoplist')->query($sql);
        //总购买次数
        $user_shop_number = 0;
        //用户购买时间
        $user_shop_time = 0;
        //得到购买码
        $user_shop_codes = '';
        $user_shop_list = M('member_go_record')->where(array('uid' => $item['q_uid'],'shopid' => $itemid,'shopqishu' => $item['qishu']))->select();
        foreach($user_shop_list as $user_shop_n){
            $user_shop_number += $user_shop_n['gonumber'];
            if($user_shop_n['huode']){
                $user_shop_time = $user_shop_n['time'];
                $user_shop_codes = $user_shop_n['goucode'];
            }
        }
        $h=abs(date("H",$item['q_end_time']));
        $i=date("i",$item['q_end_time']);
        $s=date("s",$item['q_end_time']);
        $w=substr($item['q_end_time'],11,3);
        $user_shop_time_add = $h.$i.$s.$w;
        $user_shop_fmod = fmod($user_shop_time_add*100,$item['canyurenshu']);
        $time_total = $user_shop_time_add*100;
        $user_shop_time_add = $time_total+$item['opencode'];
        if($item['q_content']){
            $item['q_content'] = unserialize($item['q_content']);
            $user_shop_time_add = $item['q_counttime'];
            $user_shop_fmod = fmod($item['q_counttime'],$item['canyurenshu']);
        }
        $user_shop_fmod = $item['q_user_code']-10000001;
        $arr = explode(',', $item['picarr']);
        if (!empty($arr)){
            $picarr = array();
            foreach ($arr as $k => $v){
                $imgs = explode('@', $v);
                $picarr[] = $imgs[0];
            }
            $item['picarr'] = $picarr;
        }else{
            $item['picarr'] = $item['thumb'];
        }
        $this->user_shop_time_add = $user_shop_time_add;
        $this->user_shop_fmod = $user_shop_fmod;
        $item['total_time'] = $time_total;
        $model = new \Think\Model();
        //记录
        $itemzx=$model->query("select * from `__PREFIX__shoplist` where `sid`='$item[sid]' and `qishu`>'$item[qishu]' and `q_end_time` is null order by `qishu` DESC LIMIT 1");
        $itemzx = current($itemzx);
        $gorecode = $model->query("select * from `__PREFIX__shoplist` where sid=".$item['sid']." and qishu < ".$item['qishu']." and q_uid is not null and q_showtime='N' order by qishu desc limit 1");
        $gorecode = current($gorecode);
        $gorecode_count=$model->query("select sum(gonumber) as count from `__PREFIX__member_go_record` where `shopid`='".$gorecode['id']."' AND `shopqishu`='".$gorecode['qishu']."' and `uid`='$gorecode[q_uid]'");
        $gorecode_count = current($gorecode_count);
        $gorecode_count=$gorecode_count ? $gorecode_count['count'] : 0;
        $gorecode_time = $model->query("select * from `__PREFIX__member_go_record` where `shopid`='".$item['id']."' AND `shopqishu`='".$item['qishu']."' and `uid`='$item[q_uid]' and `huode` = '$item[q_user_code]' limit 1");
        $gorecode_time = current($gorecode_time);
        if ($gorecode){
                $gorecode['q_user'] = unserialize($gorecode['q_user']);
                if (!file_exists($gorecode['q_user']['img'])){
                    $gorecode['q_user']['userPhoto'] = 'Upload/member.jpg';
                }
            }

        $shopitem='dataserverfun';
        $curtime=time();
        //晒单数
        $shopid=$model->query("select * from `__PREFIX__shoplist` where `id`='$itemid'");
        $shopid = current($shopid);
        $shoplist=$model->query("select * from `__PREFIX__shoplist` where `sid`='$shopid[sid]'");
        $shop='';
        foreach($shoplist as $list){
            $shop.=$list['id'].',';
        }
        $id=trim($shop,',');
        if($id){
            $shaidan=$model->query("select * from `__PREFIX__shaidan` where `sd_shopid` IN ($id)");
            $sum=0;
            foreach($shaidan as $sd){
                $shaidan_hueifu=$model->query("select * from `__PREFIX__shaidan_hueifu` where `sdhf_id`='$sd[sd_id]'");
                $sum=$sum+count($shaidan_hueifu);
            }
        }else{
            $shaidan=0;
            $sum=0;
        }
        $itemxq=0;
        if(!empty($itemzx)){
          $itemxq=1;
        }
        //用户头像
        $item['q_user'] = unserialize($item['q_user']);
        if (!file_exists($item['q_user']['userPhoto'])){
            $item['uphoto'] = 'Upload/member.jpg';
        }else{
            $item['uphoto'] = $item['q_user']['userPhoto'];
        }
        //分隔开奖号码
        $opencode = str_split($item['opencode']);
        $this->opencode = $opencode;
        $member = $this->userinfo;
        $this->item = $item;
        $this->gorecode = $gorecode;
        $this->loopqishu = $loopqishu;
        $this->user_shop_number = $user_shop_number;
        $this->gorecode_count = $gorecode_count;
        $this->user_shop_time = $user_shop_time;
        $this->gorecode_time = $gorecode_time;
        $this->shopitem = $shopitem;
        $this->itemzx = $itemzx;
        //获取云购清单
        $cartNum = count(json_decode(stripslashes(cookie('Cartlist')),true));
        $this->assign('cartNum',$cartNum);
        $this->display('Yungo/yun/goodsOld');
    }
    /************************************云购清单********************/
    //云购清单列表
    public function cartList(){
        $m = D('Yungo');
        //获取购物车列表
        $cartList = $m->getCartList();
        //提出总价
        $MoneyCount = $cartList['MoneyCount'];
        $this->assign('MoneyCount',$MoneyCount);
        //返回数组格式的商品列表
        unset($cartList['MoneyCount']);
        $this->assign('cartList',$cartList);
        //返回json格式的商品列表
        foreach($cartList as $k=>$v){
            $jsonCartList[$v['id']] = $v;
        }
        $jsonCartList['MoneyCount'] = $MoneyCount;
        $this->assign('jsonCartList',json_encode($jsonCartList));
        //获取推荐产品
        $posGoods = $m->getPosGoods();
        $this->assign('posGoods',$posGoods);
        $this->display('Yungo/yun/cartList');
    }

    //修改清单商品数量
    public function changeNum(){
        $m = D('Yungo');
        $rs = $m->changeNum();
        echo json_encode($rs);
    }
    //删除选中商品
    public function delSelete(){
        $m = D('Yungo');
        $rs = $m->delSelete();
        $this->ajaxReturn($rs);
    }
    /**************************支付列表*********************/
    //跳转到云购提交支付
    public function checkOrder(){
        $this->isLogin();
        $m = D('Yungo');
        //获取购物车列表
        $cartList = $m->getCartList();
        //提出总价
        $MoneyCount = $cartList['MoneyCount'];
        $this->assign('MoneyCount',$MoneyCount);
        //返回数组格式的商品列表
        unset($cartList['MoneyCount']);
        $this->assign('cartList',$cartList);
        //获取即将揭晓
        $rightNowGoods = $m->getRightNow();
        $this->assign('rightNowGoods',$rightNowGoods);
        //获取用户余额
        $m = M('Users');
        $USER = session('WST_USER');
        $userMoney = $m->where('userId = '.$USER['userId'])->getField('userMoney');
        $this->assign('userMoney',$userMoney);
        $this->display('Yungo/yun/checkOrder');
    }
    // 开始支付
    public function paysubmit() {
        $this->isLogin();
        $checkpay = 'money'; // 获取支付方式 fufen money bank
        $banktype = I('banktype'); // 获取选择的银行 CMBCHINA ICBC CCB
        $money = I('pay_money'); // 获取需支付金额
        $fufen = I('t'); // 获取福分
        $submitcode1 = I('submitcode'); // 获取SESSION
        $uid = $this->userinfo['uid'];dump($money);die;
       if (! empty ($submitcode1 )) {
          if (isset ($_SESSION ['submitcode'] )) {
              $submitcode2 = $_SESSION ['submitcode'];
          } else {
              $submitcode2 = null;
          }
          if ($submitcode1 == $submitcode2) {
              unset ($_SESSION["submitcode"]);
          } else {
              $this->error('请不要重复提交...');
          }
       } else {
            $this->error('正在返回购物车...');
            exit;
       }
        $zhifutype = M('Pay')->where(array('pay_class' => 'alipay'))->find();
        if (empty($zhifutype)) {
            $this->error('手机支付只支持易宝,请联系站长开通！');
        }
        $pay_checkbox = false; //钱包支付
        $pay_type_bank = false; //银行卡支付
        $pay_type_id = false;   //获取平台支付类型，支付宝，微信支付...
        if ($checkpay == 'money') {
            $pay_checkbox = true;
        }
        if ($banktype != 'nobank') {
            $pay_type_id = $banktype;
        }
        if (! empty ( $zhifutype )) {
            $pay_type_bank = $zhifutype ['pay_class'];
        }
        if (! $pay_type_id) {
            if ($checkpay != 'fufen' && $checkpay != 'money'){
                $this->error('选择支付方式');
            }
        }
        $pay = new \Go\Util\pay();
        $pay->fufen = $checkpay == 'fufen'?$fufen:0;
        $pay->pay_type_bank = $pay_type_bank;
        $ok = $pay->init($uid, $pay_type_id, 'go_record'); // 购买商品
        if ($ok == 'error'){
            $this->error('账户余额不足');
        }
        if ($ok != 'ok') {
            cookie('Cartlist',null);
            $this->error($ok."<br />购物车没有商品请");
        }
        $check = $pay->go_pay($pay_checkbox);
        if (!$check) {
            $this->error('订单添加失败');
        }
        cookie('Cartlist',null);
        if ($check) {
            header ( "location:".U('Cart/paysuccess'));
        } else {
            header ( "location:" . U('Index/index'));
        }
    }

}
?>